package proyectobdii;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;

public class DataBase {
    private String database;
    private String host;
    private String username;
    private String password;
    private String url;
    private String driver;
    private static DataBase instance;
    private Connection connection;
    private Statement statement;


    public synchronized static DataBase getInstance(String username, String password, String host, String database) throws Exception {
	if (instance == null){
		instance = new DataBase(username, password, host, database);
		try {
			instance.connect();
		} catch (Exception e) {
			throw e ;
		}
	}	
	return instance;
    }


    public DataBase(){
        database= "bdii";
        host    = "localhost";
	username= "root";
	password= "root";
	url     = "jdbc:mysql://"+host+"/"+database;
	driver  = "org.gjt.mm.mysql.Driver";//MYSQL POR DEFECTO
    }

    public DataBase(String username, String password, String host, String database) throws SQLException {
	this.database = database;
        this.host     = host;
        this.username = username;
	this.password = password;
	this.url      = "jdbc:mysql://"+host+"/"+database;
	this.driver   = "org.gjt.mm.mysql.Driver";//MYSQL POR DEFECTO
    }
   
    
    public String getPassword(){
        return this.password;
    }
    
    public String getUserName(){
        return this.username;
    }
    
    public String getDataBaseName(){
        return this.database;
    }
    
    public String getHost(){
        return this.host;
    }
    
    public Connection getConection(){
        return this.connection;
    }

    public void connect() throws Exception {
	try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
            statement = connection.createStatement();
            connection.setAutoCommit(false);
            } catch (ClassNotFoundException cnfe) {
                System.err.println("Error loading driver: " + cnfe);
                throw cnfe;
            } catch (SQLException sqle) {
		System.err.println("Error connecting: " + sqle);
		throw sqle;
            } catch (Exception e) {
		System.err.println("Error : " + e);
		throw e;
            }
    }

    public ResultSet executeQueryy(String query) throws SQLException {
	return (ResultSet) (statement.executeQuery(query));
    }

    public int executeUpdate(String query) throws SQLException {
        return (statement.executeUpdate(query));
    }

    public void commit() throws Exception {
        connection.commit();
    }

    public void rollback() throws Exception {
	connection.rollback();
    }

    public void disconect() throws Exception {
	connection.close();
    }
}
